package de.koller.reason.gui.component;

import de.koller.reason.gui.GUIRoot;
import de.koller.reason.gameGui.visual.Layer;
import de.koller.reason.gui.renderObj.IRenderPosition;
import java.util.HashSet;
import java.util.Iterator;
import java.util.Set;

public class RComponent implements IRenderPosition {
	
	private float posX = 0, posY = 0;
	private float width = 0, height = 0;
	private float layerZ = 0;
	
	private int colorGlow = 0xffffffff;
	private float glowRange = 10;
	
	private Set<RComponent> subComponents = new HashSet<>();
	private RComponent parent = null;
	
	public void addComponent( RComponent component ) {
		if( component.parent != null )
			throw new IllegalArgumentException( component + " has already a parent!" );
		
		subComponents.add( component );
		component.parent = this;
	}
	
	public void removeComponent( RComponent component ) {
		if( !subComponents.remove( component ) )
			throw new IllegalArgumentException( component + " ist not a subcomponent of " + this );
		component.parent = null;
	}

	public void setLayerZ( float layerZ ) {
		this.layerZ = layerZ;
	}

	public void setPosX( float posX ) {
		this.posX = posX;
	}

	public void setPosY( float posY ) {
		this.posY = posY;
	}

	public void setPos( float x, float y ) {
		this.setPosX( x );
		this.setPosY( y );
	}
	
	public void setHeight( float height ) {
		this.height = height;
	}

	public void setWidth( float width ) {
		this.width = width;
	}

	@Override
	public float getHeight() {
		return this.height;
	}

	@Override
	public float getWidth() {
		return this.width;
	}

	@Override
	public float getX() {
		float x = posX;
		for( Iterator<RComponent> i = new ParentIterator(); i.hasNext(); )
			x += i.next().posX;
		return x;
	}

	@Override
	public float getY() {
		float y = posY;
		for( Iterator<RComponent> i = new ParentIterator(); i.hasNext(); )
			y += i.next().posY;
		return y;
	}

	@Override
	public float getZ() {
		float lz = layerZ;
		for( Iterator<RComponent> i = new ParentIterator(); i.hasNext(); )
			lz += i.next().layerZ;
		return lz;
	}

	public int getColorGlow() {
		return colorGlow;
	}

	public void setColorGlow( int colorGlow ) {
		this.colorGlow = colorGlow;
	}

	public float getGlowRange() {
		return glowRange;
	}

	public void setGlowRange( float glowRange ) {
		this.glowRange = glowRange;
	}
	
	private class ParentIterator implements Iterator<RComponent> {
		
		private RComponent current = RComponent.this;
		
		@Override public boolean hasNext() {
			return current.parent != null;
		}

		@Override
		public RComponent next() {
			RComponent r = current.parent;
			current = current.parent;
			return r;
		}

		@Override
		public void remove() {
			throw new UnsupportedOperationException( "Not supported yet." );
		}	
	}
	
}
